package com.lzy.utils;

import java.io.*;
import java.util.*;
import java.util.concurrent.TimeUnit;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.lzy.exception.user.SessionTimeoutException;
import eu.bitwalker.useragentutils.UserAgent;
import com.lzy.constant.UserConstant;
import com.lzy.security.LoginUser;
import com.lzy.utils.ip.IpUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import io.jsonwebtoken.Claims;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.SignatureAlgorithm;

/**
 * token验证处理
 *
 * @author ruoyi
 */
@Component
public class TokenUtil
{
    // 令牌自定义标识
    @Value("${token.header}")
    private String header;

    // 令牌秘钥
    @Value("${token.secret}")
    private String secret;

    // 令牌有效期（默认30分钟）
    @Value("${token.expireTime}")
    private int expireTime;

    @Value("${token.prefix}")
    private String prefix;

    protected static final long MILLIS_SECOND = 1000;

    protected static final long MILLIS_MINUTE = 60 * MILLIS_SECOND;

    private static final Long MILLIS_MINUTE_TEN = 20 * 60 * 1000L;

    @Autowired
    private RedisCache redisCache;

    private static final ObjectMapper om = new ObjectMapper();

    /**
     * 获取用户身份信息
     *
     * @return 用户信息
     */
    public LoginUser getLoginUser(String token) throws IOException, ClassNotFoundException {
        if (StringUtil.isNotEmpty(token))
        {
            Claims claims = parseToken(token);
            // 解析对应的权限以及用户信息 // 获取用户 redis 的 key
            Long userId = Long.valueOf((Integer) claims.get(UserConstant.USER_ID));
            // 用户的key
            String userKey = getUserKey(userId, token);
            LoginUser user = redisCache.getCacheObject(userKey);
            if (StringUtil.isNull(user)) {
                throw new SessionTimeoutException("会话已经超时，请重新登陆！");
            }
            refreshToken(user, token);
            return user;
        }
        return null;
    }

    /**
     * 设置用户身份信息
     */
    /*public void setLoginUser(LoginUser loginUser)
    {
        if (Objects.isNull(loginUser))
        {
            refreshToken(loginUser);
        }
    }*/

    /**
     * 删除用户身份信息
     */
    public void delLoginUser(Long userId, String token)
    {
        if (StringUtil.isNotNull(userId))
        {
            String userKey = getUserKey(userId, token);
            String tokenKey = getTokenKey(userId);
            List<String> strings = new ArrayList<>();
            strings.add(userKey);
            strings.add(tokenKey);
            redisCache.deleteObject(strings);
        }
    }

    /**
     * 创建令牌
     *
     * @param loginUser 用户信息
     * @return 令牌
     */
    public String createToken(LoginUser loginUser) throws IOException {

        Map<String, Object> claims = new HashMap<>();
        claims.put(UserConstant.USER_ID, loginUser.getUser().getUserId());
        String token = createToken(claims);
        setUserAgent(loginUser);
        refreshToken(loginUser, token.split(" ")[1].substring(prefix.length()));
        return token;
    }

    /**
     * 验证令牌有效期，相差不足20分钟，自动刷新缓存
     *
     * @param loginUser
     * @return 令牌
     */
    public void verifyToken(LoginUser loginUser, String token) throws IOException {
        long expireTime = loginUser.getExpireTime();
        long currentTime = System.currentTimeMillis();
        if (currentTime - expireTime <= MILLIS_MINUTE_TEN)
        {
            refreshToken(loginUser, token);
        }
    }

    /**
     * 验证令牌和用户信息的有效期，相差不足20分钟，自动刷新缓存
     *
     * @param token
     * @return 令牌
     */
    public boolean verifyToken(HttpServletRequest request, HttpServletResponse response, String token) throws IOException, ClassNotFoundException {
        Claims claims = parseToken(token);

        // 在 jwt 中获取用户的 userId
        Long userId = Long.valueOf((Integer) claims.get(UserConstant.USER_ID));

        // 用户token的key
        String tokenKey = getTokenKey(userId);
        String redisToken = redisCache.getCacheObject(tokenKey);
        if (StringUtil.isEmpty(redisToken) && !token.equals(redisToken)) {
            throw new SessionTimeoutException("会话已过时，请重新登陆！");
        }

        // 用户信息的key
        String userKey = getUserKey(userId, token);
        LoginUser loginUser = redisCache.getCacheObject(userKey);
        if (StringUtil.isNull(loginUser)) {
            throw new SessionTimeoutException("会话已过时，请重新登陆！");
        }

        // 相差不足20分钟，自动刷新缓存
        long expireTime = loginUser.getExpireTime();
        long currentTime = System.currentTimeMillis();
        if (currentTime - expireTime <= MILLIS_MINUTE_TEN && !request.getRequestURI().equals(UserConstant.REFRESH_URI))
        {
            response.setHeader("isRefreshToken", "true");
        }

        return true;
    }

    /**
     * 刷新令牌有效期
     *
     * @param loginUser 登录信息
     */
    public void refreshToken(LoginUser loginUser, String token) throws IOException {
        loginUser.setLoginTime(System.currentTimeMillis());
        loginUser.setExpireTime(loginUser.getLoginTime() + expireTime * MILLIS_MINUTE);
        String userKey = getUserKey(loginUser.getUser().getUserId(), token);
        String userTokenKey = getTokenKey(loginUser.getUser().getUserId());

        String cacheObject = redisCache.getCacheObject(userTokenKey);
        if (StringUtil.isNotEmpty(cacheObject)) {
            redisCache.deleteObject(userTokenKey);
        }
        if (StringUtil.isNotNull(redisCache.getCacheObject(userKey))) {
            redisCache.deleteObject(userKey);
        }
        redisCache.setCacheObject(userTokenKey, token, expireTime, TimeUnit.MINUTES);
        redisCache.setCacheObject(userKey, loginUser, expireTime, TimeUnit.MINUTES);
    }

    /**
     * 设置用户代理信息
     *
     * @param loginUser 登录信息
     */
    public void setUserAgent(LoginUser loginUser)
    {
        UserAgent userAgent = UserAgent.parseUserAgentString(ServletUtils.getRequest().getHeader("User-Agent"));
        String ip = IpUtils.getIpAddr(ServletUtils.getRequest());
        loginUser.setIpaddr(ip);
        loginUser.setBrowser(userAgent.getBrowser().getName());
        loginUser.setOs(userAgent.getOperatingSystem().getName());
    }

    /**
     * 从数据声明生成令牌
     *
     * @param claims 数据声明
     * @return 令牌
     */
    private String createToken(Map<String, Object> claims)
    {
        Calendar instance = Calendar.getInstance();
        instance.add(Calendar.MINUTE, 30);
        String token = Jwts.builder()
                .setClaims(claims)
                .setExpiration(instance.getTime())
                .signWith(SignatureAlgorithm.HS512, secret).compact();
        return UserConstant.TOKEN_PREFIX + prefix + token;
    }

    /**
     * 从令牌中获取数据声明
     *
     * @param token 令牌
     * @return 数据声明
     */
    public Claims parseToken(String token)
    {
        return Jwts.parser()
                .setSigningKey(secret)
                .parseClaimsJws(token)
                .getBody();
    }

    /**
     * 从令牌中获取用户名
     *
     * @param token 令牌
     * @return 用户名
     */
    public String getUsernameFromToken(String token)
    {
        Claims claims = parseToken(token);
        return claims.getSubject();
    }

    /**
     * 获取请求token
     *
     * @param request
     * @return token
     */
    public String getToken(HttpServletRequest request)
    {
        String token = request.getHeader(header);
        if (StringUtil.isNotEmpty(token) && token.startsWith(UserConstant.TOKEN_PREFIX))
        {
            token = token.split(" ")[1].substring(prefix.length());;
        }
        return token;
    }

    public String getUserKey(Long userId, String token)
    {
        return UserConstant.LOGIN_TOKEN_KEY + userId + ":" + System.getProperty("os.name").split(" ")[0] + ":" + token;
    }

    public String getTokenKey(Long userId)
    {
        return UserConstant.LOGIN_TOKEN_KEY + userId + ":" + System.getProperty("os.name").split(" ")[0];
    }
}
